﻿namespace CloudNinja.Metering.Providers.SQLAzure
{
    using System;
    using System.Data.SqlClient;

    using CloudNinja.Metering.Common.Logging;

    public class TenantDatabaseBandwidth
    {
        public long DatabaseBandwidth_Ingress { get; set; }

        public long DatabaseBandwidth_Egress { get; set; }

        public static TenantDatabaseBandwidth GetTodays(string connectionString, string databaseName, ILogger logger)
        {
            var result = new TenantDatabaseBandwidth();

            // Note: This provider only works against "SQL AZure"
            //       The sys.bandwidth_usage view only exists on SQL Azure
            using (var connection = new SqlConnection(connectionString))
            {
                var command = connection.CreateCommand();
                connection.Open();

                // Time column shows the hour when the bandwidth was consumed. The query below sums the bandwidth use for all hours after today's start.
                // The returned value is in kilobytes
                command.CommandText =
                    string.Format(
                    @"select
                        convert(varchar(8),sys.bandwidth_usage.time, 1) as usage_day, direction, sum(quantity) as kiloBytes 
                    from
                        sys.bandwidth_usage
                    where
                        class = 'Internal'
                        and database_name = '{0}'
                        and convert(varchar(8),sys.bandwidth_usage.time, 1) = convert(varchar(8),getutcdate(), 1)
                    group by
                        convert(varchar(8),sys.bandwidth_usage.time, 1), direction 
                    order by
                        convert(varchar(8),sys.bandwidth_usage.time, 1), direction",
                    databaseName);

                command.CommandType = System.Data.CommandType.Text;

                using (SqlDataReader reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        var kiloBytes = Convert.ToInt64(Math.Round((decimal)reader["kiloBytes"], 0));
                        var direction = reader["direction"].ToString();

                        if (direction == "Egress")
                        {
                            result.DatabaseBandwidth_Egress = kiloBytes;
                        }
                        else if (direction == "Ingress")
                        {
                            result.DatabaseBandwidth_Ingress = kiloBytes;
                        }
                    }
                }

                return result;
            }
        }
    }
}
